package com.sky.controller.admin;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;


import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.result.Result;
import com.sky.service.DishFlavorService;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;


import java.util.ArrayList;
import java.util.List;
import java.util.Set;


/**
 * 菜品管理
 */
@RestController
@RequestMapping("/admin/dish")
@Api(tags = "菜品相关接口")
@Slf4j
public class DishController {
    @Autowired
    private DishService dishService;
    @Autowired
    private DishFlavorService dishFlavorService;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 分页查询
     */
    @ApiOperation("分页查询")
    @GetMapping("/page")
    public Result<IPage<Dish>> page(@RequestParam Integer page, @RequestParam Integer pageSize, DishPageQueryDTO dishPageQueryDTO ){
        log.info("分页查询，参数：{}",page,pageSize,dishPageQueryDTO);
        IPage<Dish> page1 = new Page<>(page,pageSize);
        IPage<Dish> pageResult = dishService.pageDish(page1,dishPageQueryDTO);
        return Result.success(pageResult);
    }

    /**
     * 新增菜品
     */
    @ApiOperation("新增菜品")
    @PostMapping
    public Result save(@RequestBody DishDTO dishDTO){
        log.info("新增菜品:{}",dishDTO);
        dishService.saveDish(dishDTO);

        // 清理该分类下的菜品缓存
        String key = "dish_" + dishDTO.getCategoryId();
        redisTemplate.delete(key);
        log.info("新增菜品后清理缓存:{}", key);

        // 清理分类列表缓存，因为可能影响分类下的菜品数量统计
        cleanCategoryCache();

        return Result.success();
    }

    /**
     * 修改菜品
     */
    @ApiOperation("更新菜品")
    @PutMapping
    public Result update(@RequestBody DishDTO dishDTO){
        log.info("修改菜品:{}",dishDTO);
        // 获取原菜品信息以确定需要清理的旧分类缓存
        Dish oldDish = dishService.getById(dishDTO.getId());
        Long oldCategoryId = oldDish.getCategoryId();

        dishService.updateDish(dishDTO);

        // 清理原分类和新分类下的菜品缓存
        if (oldCategoryId != null) {
            redisTemplate.delete("dish_" + oldCategoryId);
        }
        redisTemplate.delete("dish_" + dishDTO.getCategoryId());
        log.info("修改菜品后清理缓存: dish_{}, dish_{}", oldCategoryId, dishDTO.getCategoryId());

        // 清理分类列表缓存
        cleanCategoryCache();

        return Result.success();
    }

    /**
     * 删除菜品
     */
    @ApiOperation("删除菜品")
    @DeleteMapping
    public Result delete(@RequestParam List<Long> ids){
        log.info("删除菜品:{}",ids);

        // 获取要删除的菜品所属的分类ID
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(Dish::getId, ids);
        List<Dish> dishes = dishService.list(queryWrapper);

        dishService.removeByIds(ids);
        // 根据菜品id删除菜品口味数据
        LambdaQueryWrapper<DishFlavor> flavorQueryWrapper = new LambdaQueryWrapper<>();
        flavorQueryWrapper.in(DishFlavor::getDishId,ids);
        dishFlavorService.remove(flavorQueryWrapper);

        // 清理相关分类的菜品缓存
        for (Dish dish : dishes) {
            String key = "dish_" + dish.getCategoryId();
            redisTemplate.delete(key);
            log.info("删除菜品后清理缓存:{}", key);
        }

        // 清理分类列表缓存
        cleanCategoryCache();

        return Result.success();
    }

    /**
     * 根据id修改状态(起售/停售)
     */
    @ApiOperation("根据id修改状态")
    @PostMapping("/status/{status}")
    public Result updateStatus(@PathVariable Integer status,@RequestParam Long id){
        log.info("修改菜品状态: {}, {}", status, id);

        // 获取菜品信息以确定所属分类
        Dish dish = dishService.getById(id);
        Long categoryId = dish.getCategoryId();

        LambdaUpdateWrapper<Dish> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(Dish::getId,id);
        wrapper.set(Dish::getStatus,status);
        dishService.update(wrapper);

        // 清理该分类下的菜品缓存
        String key = "dish_" + categoryId;
        redisTemplate.delete(key);
        log.info("修改菜品状态后清理缓存:{}", key);

        return Result.success();
    }

    /**
     * 根据id查询菜品（包含口味信息）
     */
    @ApiOperation("根据id查询菜品")
    @GetMapping("/{id}")
    public Result<DishVO> getByIdWithFlavor(@PathVariable Long id){
        log.info("根据id查询菜品及口味:{}", id);
        // 查询菜品基本信息
        Dish dish = dishService.getById(id);
        if (dish == null) {
            return Result.error("菜品不存在");
        }
        // 查询菜品的口味数据
        LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DishFlavor::getDishId, id);
        List<DishFlavor> dishFlavors = dishFlavorService.list(queryWrapper);

        // 封装VO返回
        DishVO dishVO = new DishVO();
        BeanUtils.copyProperties(dish, dishVO);
        dishVO.setFlavors(dishFlavors);
        return Result.success(dishVO);
    }

    /**
     * 清理分类相关的缓存
     */
    private void cleanCategoryCache() {
        // 匹配所有分类相关的缓存key并删除
        Set<String> keys = redisTemplate.keys("category_list_*");
        if (keys != null && !keys.isEmpty()) {
            redisTemplate.delete(keys);
            log.info("清理分类缓存:{}", keys);
        }
    }
    /**
     * 根据分类id查询菜品列表
     * */
    @ApiOperation("根据分类id查询菜品")
    @GetMapping("/list")
    public Result<List<DishVO>> list(Long categoryId) {
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Dish::getCategoryId, categoryId);
        List<Dish> list = dishService.list(queryWrapper);
        ArrayList<DishVO> list1 = new ArrayList<>();
        for (Dish dish : list) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(dish, dishVO);
            list1.add(dishVO);
        }
        return Result.success(list1);
    }
}
